package com.da.lon.wang.xlg.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.da.lon.wang.xlg.MyApplication;
import com.da.lon.wang.xlg.R;
import com.da.lon.wang.xlg.constants.PreferencesConfig;
import com.da.lon.wang.xlg.util.PreferenceUtils;
import com.da.lon.wang.xlg.util.Utils;
import com.umeng.analytics.MobclickAgent;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Locale;

public class WebViewYuanActivity extends BaseActivity implements
        OnClickListener {

    private WebView webView;

    private ImageButton backButton;
    private ImageButton rightButton;
    private TextView titleTextView;
    Handler titleHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            titleTextView.setText(msg.obj.toString());
        }
    };
    private int flag;
    private String url;
    private String url_ad;
    private String merger_sn;
    private String orders_id;
    private String trade_number;
    private String title;
    private long firstTime = 0;
    private String sattr;

    /**
     * 获取网页的html代码
     *
     * @param path
     * @return
     */
    public static String getWebHtml(String path) {
        String result = "";
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(path)
                    .openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            String temp = "";
            while ((temp = reader.readLine()) != null) {
                result += temp;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        MyApplication.clearActivityList();
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.ouka_webview);
        backButton = (ImageButton) findViewById(R.id.ouka_back);
        webView = (WebView) findViewById(R.id.ouka_webview);
        backButton.setOnClickListener(this);

        rightButton = (ImageButton) findViewById(R.id.ouka_party_right);
        rightButton.setVisibility(View.GONE);
        rightButton.setOnClickListener(this);

        titleTextView = (TextView) findViewById(R.id.title);
        init();
    }

    private void init() {
        // TODO Auto-generated method stub
        Bundle bundle = this.getIntent().getExtras();
        if (null != bundle) {
            url = bundle.getString("url");
            url_ad = bundle.getString("url_ad");

            merger_sn = bundle.getString("merger_sn");
            orders_id = bundle.getString("orders_id");
            trade_number = bundle.getString("trade_number");
            flag = bundle.getInt("flag");
            sattr = bundle.getString("sattr");
        } else {
            return;
        }
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setBuiltInZoomControls(false);
        webView.getSettings().setBlockNetworkImage(false);
        webView.getSettings().setJavaScriptEnabled(true);// 启用javascript支持
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    dismissDialog();
                    setTitle(url);
                } else
                    showDialog();
            }
        });
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String path) {
                if (path.toUpperCase(Locale.CHINA).contains(// 商品跳转
                        "/p/".toUpperCase(Locale.CHINA))) {
                    Intent intent = new Intent(WebViewYuanActivity.this,
                            ProductsActivity.class);
                    String product_number;
                    if (path.indexOf(".html") != -1) {
                        product_number = path.substring(
                                path.indexOf("/p/") + 3, path.indexOf(".html"));
                    } else {
                        product_number = path.substring(
                                path.indexOf("/p/") + 3, path.length());
                    }
                    PreferenceUtils.getInstance().SetSettingString(
                            PreferencesConfig.PRODUCT_NUMBER, product_number);
                    (WebViewYuanActivity.this).startActivity(intent);
                    return true;

                } else {
                    Intent intent = new Intent(WebViewYuanActivity.this,
                            WebViewYuanActivity.class);
                    Bundle bundle = new Bundle();
                    // bundle.putInt("flag", 001);
                    bundle.putString("url", path);
                    intent.putExtras(bundle);
                    intent.setFlags(intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    WebViewYuanActivity.this.finish();
                    return true;
                }
            }
        });
        webView.loadUrl(Utils.constructUrl(url));
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();

    }

    private void setTitle(final String url) {
        new Thread() {
            @Override
            public void run() {
                String html = getWebHtml(url);
                if (html.indexOf("htitle") != -1) {
                    String temp = html.substring(html.indexOf("htitle"),
                            html.length());
                    title = temp.substring(temp.indexOf(">") + 1,
                            temp.indexOf("<"));
                    Message msg = new Message();
                    msg.obj = title;
                    titleHandler.sendMessage(msg);
                } else if (html.indexOf("new-header") != -1) {
                    String temp = html.substring(html.indexOf("new-header"),
                            html.length());
                    if (temp.contains("tb-wz")) {
                        String temp1 = temp.substring(temp.indexOf("tb-wz"),
                                temp.length());
                        title = temp1.substring(temp1.indexOf(">") + 1,
                                temp1.indexOf("<"));
                    } else if (temp.contains("i-h-x")) {
                        String temp1 = temp.substring(temp.indexOf("i-h-x"),
                                temp.length());
                        title = temp1.substring(temp1.indexOf(">") + 1,
                                temp1.indexOf("<"));
                    } else {
                        if (temp.indexOf("<h2>") != -1) {
                            title = temp.substring(temp.indexOf("<h2>") + 4,
                                    temp.indexOf("</h2>"));
                        } else {
                            title = "";
                        }
                    }
                    Message msg = new Message();
                    msg.obj = title;
                    titleHandler.sendMessage(msg);
                } else if (html.indexOf("head-tip") != -1) {
                    String temp = html.substring(html.indexOf("head-tip"),
                            html.length());
                    title = temp.substring(temp.indexOf(">") + 1,
                            temp.indexOf("<"));
                    Message msg = new Message();
                    msg.obj = title;
                    titleHandler.sendMessage(msg);
                }
            }

            ;
        }.start();
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.ouka_back:
                webView.destroy();
                finish();
                break;
            case R.id.ouka_party_right:

                try {
                    String pro_name = title;
                    String uri = url;
                    if (pro_name == null) {
                        pro_name = "";
                    }
                    if (uri == null) {
                        uri = "";
                    }
                    Utils.showShare(WebViewYuanActivity.this, pro_name, null, uri,
                            null);
                } catch (Exception e) {
                    Toast.makeText(this, "参数有误", Toast.LENGTH_SHORT).show();
                }

                break;

            default:
                break;
        }

    }
}
